
import AMapLoader from "@amap/amap-jsapi-loader";
import seeting from "@/config/seeting";

export interface Weather {
    adcode: string, // 区域编码
    city: string // 城市名
    humidity: string, // 空气湿度（百分比） "65"
    info: string, // 成功状态文字描述
    province: string, // 省份名
    reportTime: string, // 数据发布的时间 "2024-09-12 16:33:13"
    temperature: number, // 实时气温 32
    weather: string,// 天气现象 "多云"
    windDirection: string, // 风向 "东南"
    windPower: string // 风力 "≤3"
}

export const useCityWeather = () => {
    const cityWeather = ref<Weather>()
    function getWeather() {
        AMapLoader.load({
            key: seeting.mapKey, //申请好的Web端开发者 Key，调用 load 时必填
            version: "2.0", //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
            plugins: ["AMap.CitySearch", "AMap.Weather"], //需要使用的的插件列表
        }).then(AMap => {
            AMap.plugin('AMap.CitySearch', function () {
                var citySearch = new AMap.CitySearch()
                citySearch.getLocalCity(function (status: any, result: any) {
                    if (status === 'complete' && result.info === 'OK') {
                        AMap.plugin("AMap.Weather", function () {
                            //创建天气查询实例
                            var weather = new AMap.Weather();
                            //执行实时天气信息查询
                            weather.getLive(result.city, function (err: any, data: Weather) {
                                //err 正确时返回 null
                                //data 返回实时天气数据，返回数据见下表
                                if (!err) {
                                    cityWeather.value = data
                                }
                            });
                        });
                    }
                })
            })

        })
    }
    onMounted(() => {
        getWeather()
    })
    return { cityWeather }
}
